package com.kakarote.examine.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import com.kakarote.core.common.Const;
import com.kakarote.core.common.cache.CrmCacheKey;
import com.kakarote.core.entity.UserInfo;
import com.kakarote.core.feign.admin.entity.SimpleUser;
import com.kakarote.core.feign.examine.entity.ExamineDataSaveBO;
import com.kakarote.core.feign.examine.entity.ExamineFlowVO;
import com.kakarote.core.servlet.BaseServiceImpl;
import com.kakarote.core.utils.BaseUtil;
import com.kakarote.core.utils.UserUtil;
import com.kakarote.examine.constant.ExamineStatusEnum;
import com.kakarote.examine.constant.ExamineTypeEnum;
import com.kakarote.examine.entity.PO.*;
import com.kakarote.examine.mapper.ExamineFlowMemberMapper;
import com.kakarote.examine.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 审批流程指定成员记录表 服务实现类
 * </p>
 *
 * @author zhangzhiwei
 * @since 2020-11-13
 */
@Service("memberService")
public class ExamineFlowMemberServiceImpl extends BaseServiceImpl<ExamineFlowMemberMapper, ExamineFlowMember> implements IExamineFlowMemberService, ExamineTypeService {

    @Autowired
    private IExamineFlowFinalOptionalService examineFlowFinalOptionalService;

    @Autowired
    private IExamineRecordService examineRecordService;

    @Autowired
    private IExamineFlowFinalService examineFlowFinalService;

    @Autowired
    private IExamineRecordLogService examineRecordLogService;

    /**
     * 保存额外的审批流程data对象
     *
     * @param dataSaveBO data
     * @param flowId     审批流程ID
     */
    @Override
    public void saveExamineFlowData(ExamineDataSaveBO dataSaveBO, Long flowId, String batchId) {
        List<ExamineFlowMember> IExamineFlowMemberList = new ArrayList<>();
        int i = 0;

        List<SimpleUser> memberUserList = dataSaveBO.getMemberUserList();
        for (SimpleUser user : memberUserList) {
            ExamineFlowMember IExamineFlowMember = new ExamineFlowMember();
            IExamineFlowMember.setUserId(user.getUserId());
            IExamineFlowMember.setEmail(user.getOuterUserEmail());
            IExamineFlowMember.setFlowId(flowId);
            IExamineFlowMember.setSort(i++);
            IExamineFlowMember.setType(dataSaveBO.getType());
            IExamineFlowMember.setBatchId(batchId);
            IExamineFlowMemberList.add(IExamineFlowMember);
        }


        saveBatch(IExamineFlowMemberList, Const.BATCH_SAVE_SIZE);
    }


    /**
     * 通过batchId查询所有flow关联对象
     *
     * @param map     缓存对象
     * @param batchId batchId
     */
    @Override
    public void queryFlowListByBatchId(Map<String, Object> map, String batchId) {
        List<ExamineFlowMember> continuousSuperiors = lambdaQuery().eq(ExamineFlowMember::getBatchId, batchId).list();
        Map<Long, List<ExamineFlowMember>> collect = continuousSuperiors.stream().collect(Collectors.groupingBy(ExamineFlowMember::getFlowId));
        map.put(ExamineTypeEnum.MEMBER.getServerName(), collect);
    }

    /**
     * 查询详情页需要的审批详情
     *
     * @param examineFlow 当前审批流程
     * @param map         缓存的map
     * @return data
     */
    @Override
    @SuppressWarnings("unchecked")
    public ExamineFlowVO createFlowInfo(ExamineFlow examineFlow, Map<String, Object> map, List<UserInfo> allUserList, Long ownerUserId) {
        Map<Long, List<ExamineFlowMember>> collect = (Map<Long, List<ExamineFlowMember>>) map.get(ExamineTypeEnum.MEMBER.getServerName());
        List<ExamineFlowMember> flowMembers = collect.get(examineFlow.getFlowId());
        if (flowMembers == null || flowMembers.size() == 0) {
            return null;
        }
        //排序
        flowMembers.sort((Comparator.comparing(ExamineFlowMember::getSort)));
        ExamineFlowVO examineFlowVO = new ExamineFlowVO();
        examineFlowVO.setExamineType(examineFlow.getExamineType());
        examineFlowVO.setFlowId(examineFlow.getFlowId());
        examineFlowVO.setName(examineFlow.getName());
        examineFlowVO.setType(flowMembers.get(0).getType());
        examineFlowVO.setExamineErrorHandling(examineFlow.getExamineErrorHandling());


        Map<Long, List<UserInfo>> allUserMap = allUserList.stream().collect(Collectors.groupingBy(UserInfo::getUserId));
        List<SimpleUser> userList = new ArrayList<>();
        for (ExamineFlowMember flowMember : flowMembers) {
            if (flowMember.getUserId() != null) {
                userList.add(toSimPleUser(allUserMap.get(flowMember.getUserId()).get(0)));
            } else {
                SimpleUser simpleUser = new SimpleUser();
                simpleUser.setOuterUserEmail(flowMember.getEmail());
                userList.add(simpleUser);
            }
        }
        examineFlowVO.setUserList(userList);
        return examineFlowVO;
    }


    /**
     * 处理当前节点
     *
     * @param examineFlow 当前处理节点
     * @param recordId    审核记录ID
     * @param data        特殊处理数据
     * @param examine     审核对象
     * @param init        是否初始化
     * @return data
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject disposeFlow(ExamineFlow examineFlow, Long recordId, Object data, Examine examine, boolean init) {
        List<ExamineFlowMember> flowMembers = lambdaQuery().eq(ExamineFlowMember::getFlowId, examineFlow.getFlowId()).orderByAsc(ExamineFlowMember::getSort).list();

        ExamineRecord examineRecord = examineRecordService.getById(recordId);

        examineFlow.setExamineId(examineRecord.getExamineId());
        ExamineFlowFinal examineFlowFinal = examineFlowFinalService.lambdaQuery().eq(ExamineFlowFinal::getFlowId, examineFlow.getFlowId())
                .eq(ExamineFlowFinal::getRecordId, recordId).one();
        if (examineFlowFinal == null) {

            Integer maxSort = examineFlowFinalService.getMaxSort(recordId, examineRecord.getExamineId());

            examineFlowFinal = new ExamineFlowFinal();
            examineFlowFinal.setCreateTime(new Date());
            examineFlowFinal.setCreateUserId(UserUtil.getUserId());
            examineFlowFinal.setExamineId(examineFlow.getExamineId());
            examineFlowFinal.setFlowId(examineFlow.getFlowId());
            examineFlowFinal.setRecordId(recordId);
            examineFlowFinal.setName(examineFlow.getName());
            examineFlowFinal.setExamineType(examineFlow.getExamineType());
            examineFlowFinal.setType(flowMembers.get(0).getType());
            examineFlowFinal.setExamineErrorHandling(examineFlow.getExamineErrorHandling());
            examineFlowFinal.setSort(maxSort + 1);
            examineFlowFinalService.save(examineFlowFinal);
        }
        List<ExamineFlowFinalOptional> userList = examineFlowFinalOptionalService.lambdaQuery().eq(ExamineFlowFinalOptional::getRecordId, recordId)
                .eq(ExamineFlowFinalOptional::getFlowId, examineFlow.getFlowId()).list();
        if (userList == null || userList.size() == 0) {
            userList = new ArrayList<>();
            for (int i = 0; i < flowMembers.size(); i++) {
                ExamineFlowMember examineFlowMember = flowMembers.get(i);
                ExamineFlowFinalOptional examineFlowFinalOptional = new ExamineFlowFinalOptional();
                examineFlowFinalOptional.setCreateTime(new Date());
                examineFlowFinalOptional.setCreateUserId(UserUtil.getUserId());
                examineFlowFinalOptional.setFlowId(examineFlow.getFlowId());
                examineFlowFinalOptional.setRecordId(recordId);
                examineFlowFinalOptional.setSort(i + 1);
                examineFlowFinalOptional.setType(examineFlowMember.getType());
                examineFlowFinalOptional.setUserId(examineFlowMember.getUserId());
                examineFlowFinalOptional.setEmail(examineFlowMember.getEmail());
                userList.add(examineFlowFinalOptional);
            }
            examineFlowFinalOptionalService.saveBatch(userList);
        }

        String batchId = IdUtil.simpleUUID();
        LocalDateTime now = LocalDateTimeUtil.now();
        List<ExamineRecordLog> recordLogs = new ArrayList<>();
        for (ExamineFlowFinalOptional examineFlowFinalUser : userList) {
            ExamineRecordLog examineRecordLog = new ExamineRecordLog();
            examineRecordLog.setLogId(BaseUtil.getNextId());
            examineRecordLog.setType(examineFlowFinal.getType());
            examineRecordLog.setCreateTime(now);
            examineRecordLog.setExamineTime(now);
            examineRecordLog.setUpdateTime(null);
            examineRecordLog.setCreateUserId(UserUtil.getUserId());
            examineRecordLog.setExamineId(examineFlowFinal.getExamineId());
            examineRecordLog.setExamineRoleId(0L);
            //   在这块判断审核人状态，是否有效等
            examineRecordLog.setExamineUserId(examineFlowFinalUser.getUserId());
            examineRecordLog.setExamineUserEmail(examineFlowFinalUser.getEmail());
            if (examineFlowFinal.getType() == 1) {
                if (userList.indexOf(examineFlowFinalUser) == 0) {
                    examineRecordLog.setExamineStatus(ExamineStatusEnum.UNDERWAY.getStatus());
                } else {
                    examineRecordLog.setExamineStatus(ExamineStatusEnum.AWAIT.getStatus());
                }
            } else {
                examineRecordLog.setExamineStatus(ExamineStatusEnum.UNDERWAY.getStatus());

            }
            if (ObjectUtil.isNotNull(examineFlowFinalUser.getUserId())) {
                BaseUtil.getRedis().del(CrmCacheKey.CRM_BACKLOG_NUM_CACHE_KEY + examineFlowFinalUser.getUserId().toString());
            }
            examineRecordLog.setFlowId(examineFlowFinal.getFlowId());
            examineRecordLog.setRecordId(recordId);
            examineRecordLog.setSort(examineFlowFinalUser.getSort());
            examineRecordLog.setBatchId(batchId);
            recordLogs.add(examineRecordLog);
        }
        examineRecordLogService.saveBatch(recordLogs);
        return new JSONObject().putOpt("status", ExamineStatusEnum.UNDERWAY.getStatus());

    }
}
